package cemp.service;

import cemp.constant.WxConstant;
import cemp.consts.WxUrlConst;
import cemp.dto.ro.WxLoginResponseDto;
import cemp.entity.StockDailyMessage;
import cemp.enums.MessageEnum;
import cemp.mapper.StockDailyMessageMapper;
import cemp.util.UrlUtils;
import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xshibai
 * @date 2025年07月25日 15:05
 */
@Service
@RequiredArgsConstructor
public class WxAuthService {

    private final RestTemplate restTemplate;

    private final WxMessageService wxMessageService;

    private final StockDailyMessageMapper messageMapper;

    /**
     * wx.login 后的jscode 转换成微信登录的用户信息 openid sessioncode等
     * @param authCode
     * @return
     */
    public WxLoginResponseDto code2Session(String authCode){
        Map<String,String> params = new HashMap<>();
        params.put("appid","wxbe755cdee15ccfd8");
        params.put("secret","72ce7874171c1eec85715846edf37c9b");
        params.put("js_code",authCode);
        params.put("grant_type","authorization_code");
        String url = UrlUtils.urlJoin(WxUrlConst.WX_URL_CODE2SESSION,params);
        String response = restTemplate.getForObject(url,String.class);
        JSONObject obj = JSONObject.parseObject(response);
        return WxLoginResponseDto.builder()
                .seesionCode(obj.getString("session_key"))
                .openid(obj.getString("openid"))
                .build();
    }

    public void sendWxMessage(String openid,Map<String,Object> miniParams,String type){
        MessageEnum messageEnum = MessageEnum.fromCode(type);
        String templateId = messageEnum.getTemplateid();
        wxMessageService.miniSend(openid,templateId,miniParams);
        //消息落地
        StockDailyMessage message = consMsg(miniParams,type);
        messageMapper.insert(message);

    }

    private StockDailyMessage consMsg(Map<String,Object> miniParams , String type){
        StockDailyMessage message = new StockDailyMessage();
        message.setIsread(0);
        message.setCreateTime(new Date());
        if(MessageEnum.COME_NOTIFY.getCode().equals(type)){
            message.setTitle(MessageEnum.COME_NOTIFY.getName());
            message.setContent(String.format("%s:已完成签到.",miniParams.get("name3")));
        }else if(MessageEnum.TASK_INFORM.getCode().equals(type)){
            message.setTitle(MessageEnum.TASK_INFORM.getName());
            message.setContent(String.format("未完成任务:%s,%s",miniParams.get("thing9"),miniParams.get("thing11")));
        }
        return message;
    }


}
